const express = require("express");
const router = express.Router();
const db = require("../sql");
// 更新或添加公告
router.post("/", async (req, res) => {
  try {
    const { content } = req.body;
    if (!content) {
      return res.json({ success: false, data: "Content is required." });
    }

    const checkSql = "SELECT COUNT(*) AS count FROM notice";
    const checkResult = await db.query(checkSql);
    const exists = checkResult[0].count > 0;

    if (exists) {
      const updateSql =
        "UPDATE notice SET content = ?, createTime = CURRENT_TIMESTAMP";
      await db.query(updateSql, [content]);
      res.json({ success: true, data: "Record updated successfully." });
    } else {
      const insertSql = "INSERT INTO notice (content) VALUES (?)";
      await db.query(insertSql, [content]);
      res.json({ success: true, data: "Record inserted successfully." });
    }
  } catch (error) {
    res.json({ success: false, data: error.message });
  }
});

// 获取所有记录

// 获取公告或创建一个空的公告
router.get("/", async (req, res) => {
  try {
    const checkSql = "SELECT * FROM notice";
    let result = await db.query(checkSql);

    if (result.length === 0) {
      // 没有记录，插入一条空内容的记录
      const insertSql = "INSERT INTO notice (content) VALUES (?)";
      await db.query(insertSql, [""]);
      // 再次查询以获取新插入的记录
      result = await db.query(checkSql);
    }

    // 返回查询到的记录
    res.json({ success: true, data: result[0] });
  } catch (error) {
    res.json({ success: false, data: error.message });
  }
});

module.exports = router;
